import React, { useEffect, useState } from 'react'
import axios from '../../aixos'
import { Space, Button, Modal, Form, Input, Table } from 'antd';
// import Table from '../../components/Table/Table'

export default function Page(props) {
  console.log(props)
  const [pageList, setPageList] = useState([])
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('')
  const [editRecordId, setEditRecordId] = useState(null)

  const [parentId, setParentId] = useState(null)

  const getList = () => {
    axios.get('/page').then(res => {
      console.log(res)
      setPageList(res.data)
    })
  }

  useEffect(() => {
    getList()
  }, [])
  const columns = [
    {
      title: '页面名称',
      dataIndex: 'title'
    },
    {
      title: '页面路径',
      dataIndex: 'path'
    },
    {
      title: '操作',
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => addChild(record._id)}>添加</Button>
          <Button type='primary' onClick={() => edit(record)}>编辑</Button>
          <Button type='danger' onClick={() => del(record._id)}>删除</Button>
        </Space>
      ),
    },
  ]
  const add = () => {
    setModalTitle('添加')
    form.resetFields()
    setIsModalVisible(true);
  }
  // 添加下级页面
  const addChild = (id) => {
    setModalTitle('添加子页面')
    form.resetFields()
    setIsModalVisible(true);
    setParentId(id)
  }
  const edit = (record) => {
    setModalTitle('编辑')
    setEditRecordId(record._id)
    form.setFieldsValue({...record})
    setIsModalVisible(true)
  }
  const del = (id) => {
    axios.delete('/page', {
      id
    }).then(() => {
      // setPageList(pageList.filter(item => item._id !==id))
      // props.history.go(0)
      getList()
    })
  }

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const onFinish = (values) => {
    console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  

  const handleOk = async () => {
    console.log(form)
    const formData = await form.validateFields()
    if (parentId) {
      // 添加子页面
      axios.post('/page', {
        parentId,
        ...formData
      }).then(() => {
        setIsModalVisible(false)
        getList()
        // setPageList(pageList.map(item => {
        //   if (item._id === parentId) {
        //     return {
        //       ...item,
        //       children: [res.data, ...item.children]
        //     }
        //   }
        //   return item
        // }))
        // setIsModalVisible(false)
        // props.history.go(0)
      })
    } else if (!editRecordId) {
      // 添加一级页面
      axios.post('/page', formData).then(res => {
        setPageList([res.data, ...pageList])
        setIsModalVisible(false)
      })
    } else {
      // 编辑
      axios.put('/page', {
        id: editRecordId,
        ...formData
      }).then(() => {
        // setPageList(pageList.map(item => {
        //   if (item._id === editRecordId) return { ...item, ...formData } 
        //   return item
        // }))
        // setIsModalVisible(false)
        // props.history.go(0)
        setIsModalVisible(false)
        getList()
      })
    }
  };
  const [form] = Form.useForm();
  return (
    <div>
      <Button onClick={add}>添加</Button>
      <Table  rowKey='_id' columns={columns} dataSource={pageList}></Table>
      <Modal title={modalTitle} cancelText='取消' okText='确认'
        visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <Form
          form={form}
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="页面名称"
            name="title"
            rules={[
              {
                required: true,
                message: 'Please input your username!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="页面路径"
            name="path"
            rules={[
              {
                required: true,
                message: 'Please input your password!',
              },
            ]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
